package com.xe.gae;


import java.util.Date;
import java.util.Map;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.xe.ResourceManager;
import com.xe.core.XEConstants;
import com.xe.core.XEResource;

public class XEResourceManager4GAE implements ResourceManager {

	
	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	Map<String,String> config;

	
	
	@Override
	public XEResource load(String path) {
		String entityClass=XEConstants.EXTREME_ENGINE_RESOURCE_FILE_NAME;
		Key key = KeyFactory.createKey(entityClass, path);
		try {
			Entity entity = datastore.get(key);
			String rpath=(String)entity.getProperty("path");
			String rtype=(String)entity.getProperty("type");
			Object osource = entity.getProperty("source");
			Object updateDate= entity.getProperty("updateDate");
			String rsource;
			if(osource instanceof  Text) {
				rsource=((Text)osource).getValue();
			}
			else {
				rsource=(String) osource;
			}
			XEResource resource = new XEResource(rpath,rtype);
			resource.setSource(rsource);
			return resource;
		} catch (EntityNotFoundException e) {
			//e.printStackTrace();
			return null;
		}

	}

	@Override
	public void save(XEResource resource) {
		String entityClass=XEConstants.EXTREME_ENGINE_RESOURCE_FILE_NAME;
		String rpath=resource.getPath();
		String rsource=resource.getSource();
		String rtype=resource.getType();
		Date uDate=new Date();

		Key key = KeyFactory.createKey(entityClass, rpath);
		Entity entity = new Entity(key);
		entity.setProperty("path", rpath);
		if (rsource.length()<500){
			entity.setProperty("source", rsource);
		}
		else{
			entity.setProperty("source", new Text(rsource));
		}
		entity.setProperty("type", rtype);
		entity.setProperty("updateDate", uDate);
		datastore.put(entity); 
	}

	
}
